package com.heima.search.listener;

import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.search.feign.ArticleFeign;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ArticleSearchService articleSearchService;

    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addArticle(String articleId){
        Map map = articleFeign.findArticle(Long.valueOf(articleId));
        try {
            articleSearchService.saveArticle(articleId,map);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章失败  文章ID==>{}",articleId);
        }
    }


    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE)
    public void deleteArticle(String articleId){
        try {
            articleSearchService.deleteArticle(articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章失败  文章ID==>{}",articleId);
        }
    }
}
